module service.HistoryService;

import message.MsgDefine;
import model;
import repository;
import hunt.logging;
import std.conv : to;
import std.base64;

class HistoryService {

  static void putHistoryMsg(Msg msg)
  {
      HistoryRepository repo = new HistoryRepository;
      repo.putHistoryMsg(msg);
  }

  static SessionListRes getSessionList(string id)
  {
      HistoryRepository repo = new HistoryRepository;
      SessionListRes res = new SessionListRes;
      FriendRepository friendRep = new FriendRepository;
      UserRepository userRep = new UserRepository;
      GroupRepository groupRep = new GroupRepository;
      repo.getSessionList(id,res);
      foreach(Sessions s;res.sessions)
      {
           auto friend = friendRep.findByChatId(to!int(s.chatId),to!int(id));
           if (friend !is null)
           {
                if (friend.aliasName.length != 0)
                {
                    s.title = friend.aliasName;
                }else{
                    auto user = userRep.findAllByUID(to!string(friend.friendId));
                    if(user !is null)
                    {
                        s.title = user.nickname;
                    }
                }
           }else
           {
                auto group = groupRep.findByUid(to!int(s.chatId));
                if (group !is null)
                {
                      s.title = group.aliasName;
                }
           }
          logInfof("Sessions : %s",s.chatId);
      }
      return res;
  }

  static Msg[] getHistoryMsg(HistoryMsgREQ req)
  {
      HistoryRepository repo = new HistoryRepository;
      HistoryMsg[] hisoryMsgs =  repo.getHistoryLimit(req);
      Msg[] rt;
      foreach(HistoryMsg omsg ; hisoryMsgs)
      {
          if (omsg.backoff == 1)
          {
              continue;
          }

          Msg msg = new Msg;
          msg.chatId = omsg.chatId;
          msg.fromUserId = omsg.fromId;
          msg.messageId = omsg.messageId;
          msg.message = omsg.message;
          msg.localId = omsg.toId;
          msg.duration = omsg.duration;
          msg.ossObjectName = omsg.ossObjectName;
          msg.fileSize = omsg.fileSize;
          msg.msgTime = to!long(omsg.createTime);
          msg.type = cast(MsgType)(omsg.type);
          msg.binaryBase64 = cast(string) Base64.decode(  omsg.binaryData );
          rt ~= msg;
      }
      return rt;
  }

}

